#include "videowindow.h"
#include "ui_videowindow.h"
#include <QFileDialog>
#include <QFileInfo>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>

VideoWindow::VideoWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::VideoWindow)
{
    ui->setupUi(this);
    //设置播放按钮mode=pause
    ui->btn_play->setProperty("mode","pause");
    //本地
    //播放视频
    this->player=new QMediaPlayer();
    //创建播放列表
    this->playlist=new QMediaPlaylist;
    this->player->setPlaylist(playlist);

    //在线
    //在线播放
    this->onlineplayer=new QMediaPlayer();
    //创建在线播放列表
    this->onlineplaylist=new QMediaPlaylist;
    //在线播放列表添加个播放对象
    this->onlineplayer->setPlaylist(onlineplaylist);

    //视频播放窗口
    this->videoWidget=new QVideoWidget(this);
    //设置展示区域
    ui->video_show->addWidget(videoWidget);

    //播放列表添加个播放对象
    this->player->setVideoOutput(this->videoWidget);

    //在线
    this->onlineplayer->setVideoOutput(this->videoWidget);
    //计算进度条进度
    connect(this->player,&QMediaPlayer::durationChanged,this,&VideoWindow::setTotal);
    connect(this->player,&QMediaPlayer::positionChanged,this,&VideoWindow::setPosition);
    connect(this->onlineplayer,&QMediaPlayer::durationChanged,this,&VideoWindow::setTotal);
    connect(this->onlineplayer,&QMediaPlayer::positionChanged,this,&VideoWindow::setPosition);

    //获取在线音乐列表
    QNetworkAccessManager *manager=new QNetworkAccessManager;
    manager->get(QNetworkRequest(QUrl("http://localhost/video.json")));
    connect(manager,&QNetworkAccessManager::finished,this,&VideoWindow::onlineVideoShow);

    //安装退出全屏事件过滤器
    this->exitevent=new ExitFullScreenEvent;
    this->videoWidget->installEventFilter(this->exitevent);
    //绑定
    connect(this->exitevent,&ExitFullScreenEvent::ExitFullScreen,this,&VideoWindow::ExitFullScreen);

    //创建数据库链接
    QSqlDatabase db=QSqlDatabase::addDatabase("QSQLITE","sqlite");
    db.setDatabaseName("D:\\VM share\\qt\\carStytem\\SQLite\\video.db");
    if(!db.open()){
        qDebug()<<"数据库打开失败";
    }
    LocalVideoDatabase();
}

VideoWindow::~VideoWindow()
{
    delete ui;
}

void VideoWindow::updateBtnMode()
{
    QString mode=ui->btn_play->property("mode").toString();
    if(mode=="pause"){
        ui->btn_play->setProperty("mode","play");
        //先卸载这个按钮
        ui->btn_play->style()->unpolish(ui->btn_play);
        //重新安装
        ui->btn_play->style()->polish(ui->btn_play);
        //调用安装后的
        ui->btn_play->update();
    }
}

void VideoWindow::LocalVideoDatabase()
{
    QSqlQuery query("SELECT title,path FROM video_local");
    while (query.next()) {
        QString title=query.value(0).toString();
        QString path=query.value(1).toString();
        ui->localList->addItem(title);
        this->playlist->addMedia(QMediaContent(QUrl::fromLocalFile(path)));
    }
}

void VideoWindow::on_btn_play_clicked()
{
    QString mode=ui->btn_play->property("mode").toString();
    if(mode=="pause"){
        ui->btn_play->setProperty("mode", "play");

        // 检查当前选中的是本地音乐还是在线音乐
        if (ui->localList->currentRow() != -1) {
            // 播放本地音乐
            this->onlineplayer->pause(); // 先暂停在线音乐
            this->player->play();
        } else if (ui->onlineList->currentRow() != -1) {
            // 播放在线音乐
            this->player->pause(); // 先暂停本地音乐
            this->onlineplayer->play();
            this->player->pause(); // 暂停本地视频
        }
    }else{
        ui->btn_play->setProperty("mode","pause");
        this->player->pause();
        this->onlineplayer->pause();
    }
    //先卸载这个按钮
    ui->btn_play->style()->unpolish(ui->btn_play);
    //重新安装
    ui->btn_play->style()->polish(ui->btn_play);
    //调用安装后的
    ui->btn_play->update();
}


void VideoWindow::on_btn_load_clicked()
{
    QSqlQuery query;
    QStringList lists=QFileDialog::getOpenFileNames(this,tr("选择视频"),tr("C:\\Users\\ASUS\\Desktop\\video"),tr("*.mp4 *.avi"));
    for (QString path:lists) {
        QFileInfo fileinfo(path);
        ui->localList->addItem(fileinfo.fileName());
        this->playlist->addMedia(QMediaContent(QUrl::fromLocalFile(path)));

        //将文件信息放到数据库中
        QString sql=QString("INSERT INTO video_local (title, path) VALUES ('%1','%2')")
                .arg(fileinfo.fileName())
                .arg(path);

        if(!query.exec(sql)){
            qDebug()<<"添加失败"<<query.lastError();
        }
    }
}

//双击播放
void VideoWindow::on_localList_itemDoubleClicked(QListWidgetItem *item)
{
    int index=this->playlist->currentIndex();
    this->playlist->setCurrentIndex(index);
    //切换后立即播放
    // 先暂停在线音乐
    this->onlineplayer->pause();
    ui->onlineList->clearSelection(); // 清除在线列表的选中状态
    this->player->play();
    this->updateBtnMode();
}


void VideoWindow::on_btn_next_clicked()
{
    // 判断当前选中的是本地音乐还是在线音乐
    if (ui->localList->currentRow() != -1) {
        // 播放本地音乐的下一首
        int index = this->playlist->currentIndex();
        if (index == this->playlist->mediaCount()-1) {
            index = 0;
        } else {
            index++;
        }
        this->playlist->setCurrentIndex(index);
        ui->localList->setCurrentRow(index);

        this->onlineplayer->pause(); // 确保在线音乐暂停
        this->player->play();
    } else if (ui->onlineList->currentRow() != -1) {
        // 播放在线音乐的下一首
        int indexonline = this->onlineplaylist->currentIndex();
        if (indexonline == this->onlineplaylist->mediaCount()-1) {
            indexonline = 0;
        } else {
            indexonline++;
        }
        this->onlineplaylist->setCurrentIndex(indexonline);
        ui->onlineList->setCurrentRow(indexonline);

        this->player->pause(); // 确保本地音乐暂停
        this->onlineplayer->play();
    }
    //如果是暂停设置为播放
    this->updateBtnMode();
}


void VideoWindow::on_btn_pre_clicked()
{
    // 判断当前选中的是本地音乐还是在线音乐
    if (ui->localList->currentRow() != -1) {
        // 播放本地音乐的上一首
        int index = this->playlist->currentIndex();
        if (index == 0) {
            index = this->playlist->mediaCount()-1;
        } else {
            index--;
        }
        this->playlist->setCurrentIndex(index);
        ui->localList->setCurrentRow(index);

        this->onlineplayer->pause(); // 确保在线音乐暂停
        this->player->play();
    } else if (ui->onlineList->currentRow() != -1) {
        // 播放在线音乐的上一首
        int indexonline = this->onlineplaylist->currentIndex();
        if (indexonline == 0) {
            indexonline = this->onlineplaylist->mediaCount()-1;
        } else {
            indexonline--;
        }
        this->onlineplaylist->setCurrentIndex(indexonline);
        ui->onlineList->setCurrentRow(indexonline);

        this->player->pause(); // 确保本地音乐暂停
        this->onlineplayer->play();
    }
    //如果是暂停设置为播放
    this->updateBtnMode();
}

void VideoWindow::setTotal(qint64 duration)
{
    this->total=duration;
}

void VideoWindow::setPosition(qint64 position)
{
    if(this->total>0){
        int progress=position*100/this->total;
        ui->progress_bar->setValue(progress);
    }
}

void VideoWindow::on_pushButton_clicked()
{
    this->parentWidget()->show();
    this->hide();
}


void VideoWindow::on_progress_bar_sliderReleased()
{
    int value=ui->progress_bar->value();

    //通过进度条计算播放进度
    int postion=value*this->total/100;
    this->player->setPosition(postion);
    this->onlineplayer->setPosition(postion);
}

void VideoWindow::on_btn_fullscreen_clicked()
{
    //将视频窗口升级为顶层窗口
    this->videoWidget->setWindowFlags(Qt::Window);
    //全屏展示
    this->videoWidget->showFullScreen();
}

void VideoWindow::ExitFullScreen()
{
    this->videoWidget->setWindowFlags(Qt::SubWindow);
    //退出全屏
    this->videoWidget->showNormal();
}

void VideoWindow::onlineVideoShow(QNetworkReply *reply)
{
    QByteArray data = reply->readAll();
    // 解析json字符串，获取视频信息，将视频路径加入到QMediaPlaylist
    // 然后使用QMediaPlayer做播放/暂停
    // 解析json字符串，获取视频信息
       QJsonDocument jsonDoc = QJsonDocument::fromJson(data);
       if (jsonDoc.isArray()) {
       QJsonArray jsonArray = jsonDoc.array();
       for (const QJsonValue &value : jsonArray) {
        if (value.isObject()) {
            QJsonObject videoObject = value.toObject();
            QString videoName = videoObject["name"].toString(); // 获取歌曲名称
            QString videoPath = videoObject["path"].toString(); // 获取歌曲路径

            // 打印歌曲名称、作者和路径
            //qDebug() << "Song Name:" << songName << ", Author:" << songAuthor << ", Path:" << songPath;

            // 将歌曲信息添加到 onlineList 中
            ui->onlineList->addItem(videoName);

            // 将歌曲路径添加到播放列表
            this->onlineplaylist->addMedia(QMediaContent(QUrl(videoPath)));
        }
     }
       }
}

void VideoWindow::on_onlineList_itemDoubleClicked(QListWidgetItem *item)
{
    int index=ui->onlineList->currentRow();
    this->onlineplaylist->setCurrentIndex(index);
    //切换后立即播放
    this->player->pause();
    ui->localList->clearSelection(); // 清除本地列表的选中状态
    this->onlineplayer->play();
    this->updateBtnMode();
}

